/*
 *  Copyright 2009 rohanranade.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */
package com.google.code.jqif;

import com.google.code.jqif.util.Params;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;

/**
 * A source of QIF which reads from a QIF file on disk
 * 
 * @author Rohan Ranade
 */
public class ReaderBasedQIFSource implements QIFSource {

    private final BufferedReader bufferedReader;
    private static final int MARK_READ_AHEAD_LIMIT = 1024 * 4;

    public ReaderBasedQIFSource(Reader reader) {
        Params.checkNotNull(reader);
        bufferedReader = new BufferedReader(reader);
    }

    public String readLine() throws IOException {
        while (true) {
            String lineText = bufferedReader.readLine();
            if (lineText == null) {
                return null;
            }
            lineText = lineText.trim();
            if (lineText == null || lineText.length() == 0) {
                continue;
            }
            return lineText;
        }
    }

    public String peekLine() throws IOException {
        bufferedReader.mark(MARK_READ_AHEAD_LIMIT);
        String lineText = readLine();
        bufferedReader.reset();
        return lineText;
    }

    public void close() {
        try {
            bufferedReader.close();
        } catch (IOException ex) {
            // swallow it
        }
    }
}
